package pers.feng1240.blog.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/*
 * 图片上传
 */
public class FileUpload {

    /*
     * 上传theme图片
     */
    public static String uploadPic(MultipartFile file, HttpServletRequest request) {
    	String dateDir =  new SimpleDateFormat("YYYYMMdd").format(new Date());  //日期
 	    String imgAbsDir = request.getSession().getServletContext().getRealPath("/upload/blog")+"/"+dateDir; //绝对路径
 	    String imgRelDir = request.getSession().getServletContext().getContextPath()+"/upload/blog/"+dateDir;  //相对路径
        String fileName = file.getOriginalFilename().toLowerCase().split("\\.")[1];;  //获取文件格式
         
        //判断文件格式
        // if("jpg".equals(fileName)){
        //     
        // }
         
         String imgName = System.currentTimeMillis()+"."+fileName; ////时间戳更改图片名称

         File targetFile = new File(imgAbsDir, imgName);  
         if(!targetFile.exists()){  
             targetFile.mkdirs();  
         }  
   
         //保存  
         try {  
             file.transferTo(targetFile);  
         } catch (Exception e) {  
             e.printStackTrace();  
         }
		return imgRelDir+"/"+imgName;   //保存相对路径
      
    }

}
